﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MShop.Core.Domain;
using System.Web.Mvc;
using MShop.Core.Extensions;

namespace MShop.Core.DataAccess
{
    public class DictDao:CommonDao<Dictionary>,IDictDao
    {
        public DictDao(IObjectContextProvider provider)
            : base(provider)
        {
            
        }

        #region IDictDao Members

        public IQueryable<Dictionary> GetByTypeId(int typeId)
        {
            var q = from item in GetAll() where item.TypeId == typeId select item;
            return q;

           
        }


        public IList<System.Web.Mvc.SelectListItem> ToSelectListItem(string typeid)
        {
            var query = GetAll().GroupBy(x => new { x.TypeId, x.TypeName });
            List<SelectListItem> list = new List<SelectListItem>();
            foreach (var k in query)
            {
                list.Add(new SelectListItem() { Text = k.Key.TypeName, Value = k.Key.TypeId.ToString() });
            }
            
            if (!string.IsNullOrEmpty(typeid))
            {

                var sel = list.Find(x => x.Value == typeid);
                if (sel != null)
                {
                    sel.Selected = true;
                }
            }

            return list;
        }

      


        public IList<SelectListItem> ToSelectListItem(int typeid, object selectedValue)
        {
            var query = GetAll().Where(x => x.TypeId == typeid);


            return query.ConvertListItem("Key", "Value", selectedValue);
        }
         


        public string GetKeyName(int typeid, int value)
        {
            var key = GetAll().Where(x => x.TypeId == typeid).FirstOrDefault(x=>x.Value==value);
            if (key != null)
                return key.Key;
            return string.Empty;
        }

        #endregion
    }
}